package com.tancw.cloud.order.controller;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.tancw.cloud.common.Result;
import com.tancw.cloud.order.entity.Order;
import com.tancw.cloud.order.feign.ProductFeignClient;
import com.tancw.cloud.order.feign.UserFeignClient;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;

/**
 * 订单控制器
 */
@Slf4j
@RestController
@RequestMapping
@RequiredArgsConstructor
public class OrderController {

    private final UserFeignClient userFeignClient;
    private final ProductFeignClient productFeignClient;

    @PostMapping("/create")
    @SentinelResource(value = "createOrder")
    public Result<Order> createOrder(@RequestBody Order order) {
        log.info("创建订单: userId={}, productId={}", order.getUserId(), order.getProductId());

        // 调用用户服务验证用户
        Result<?> userResult = userFeignClient.getUserById(order.getUserId());
        log.info("用户信息: {}", userResult);

        // 调用商品服务验证商品
        Result<?> productResult = productFeignClient.getProductById(order.getProductId());
        log.info("商品信息: {}", productResult);

        // 创建订单
        order.setOrderNo("ORD" + System.currentTimeMillis() + RandomUtil.randomNumbers(4));
        order.setStatus(0);
        order.setTotalAmount(BigDecimal.valueOf(100.00));
        order.setCreateTime(LocalDateTime.now());
        
        // TODO: 保存订单到数据库

        return Result.success(order);
    }

    @GetMapping("/{id}")
    public Result<Order> getOrderById(@PathVariable Long id) {
        log.info("查询订单: {}", id);
        // TODO: 从数据库查询订单
        Order order = new Order();
        order.setId(id);
        order.setOrderNo("ORD" + System.currentTimeMillis());
        return Result.success(order);
    }
}
